<template>
  <div>
    <!-- 时间区间选择框 -->
    <el-select v-model="selectedRange" placeholder="请选择时间区间" @change="fetchData">
      <el-option label="近三天" value="3d"></el-option>
      <el-option label="近一周" value="7d"></el-option>
      <el-option label="近一个月" value="30d"></el-option>
    </el-select>
    <!-- eCharts 图表容器 -->
    <div ref="chartRef" style="width: 100%; height: 400px;"></div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue';
import * as echarts from 'echarts';
import axios from 'axios';
import querystring from 'querystring';
// 时间区间选择值
const selectedRange = ref('3d');
// eCharts 图表引用
const chartRef = ref(null);
// 图表实例
let chart = null;

// 计算开始和结束日期
const calculateDateRange = (range) => {
  const endDate = new Date();
  let startDate = new Date();
  switch (range) {
    case '3d':
      startDate.setDate(endDate.getDate() - 3);
      break;
    case '7d':
      startDate.setDate(endDate.getDate() - 7);
      break;
    case '30d':
      startDate.setDate(endDate.getDate() - 30);
      break;
  }
  const formatDate = (date) => {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
  };
  return {
    startDate: formatDate(startDate),
    endDate: formatDate(endDate)
  };
};

// 获取数据
const fetchData = async () => {
  const { startDate, endDate } = calculateDateRange(selectedRange.value);
  try {
    const response = await axios.get('/api/admin/statistics/client', {
      params: {
        startDate,
        endDate
      }
    });
    const data = response.data.data;
    updateChart(data);
  } catch (error) {
    console.error('获取数据失败:', error);
  }
};

// 更新图表
const updateChart = (data) => {
  const dates = data.map(item => item.date);
  const counts = data.map(item => item.count);

  const option = {
    xAxis: {
      type: 'category',
      data: dates
    },
    yAxis: {
      type: 'value'
    },
    series: [{
      data: counts,
      type: 'line'
    }]
  };

  chart.setOption(option);
};

onMounted(() => {
  // 初始化 eCharts 图表
  chart = echarts.init(chartRef.value);
  fetchData();
});

// 监听时间区间选择变化
watch(selectedRange, fetchData);
</script>

<style scoped>
/* 这里可以添加统计后台页面的样式 */
</style>